import 'package:dartx/dartx.dart';
import 'package:easy_device_info/easy_device_info.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:realm/realm.dart';
import 'package:sgy_flutter/database/device_entity.dart';
import 'package:sgy_flutter/extensions/get.dart';
import 'package:sgy_flutter/model/device_model.dart';
import 'package:sgy_flutter/widget/app_dialog.dart';

class ScanLogic extends GetxController {
  Stream<List<DeviceModel>> get scanResults =>
      bleManager.scanResults.stream.map(DeviceModel.filterRightPart);

  Future startScan() async {

    await bleManager.startScan();
  }

  @override
  void onReady() async{


    startScan();
    super.onReady();
  }

  void handleDeviceModelTap(DeviceModel model) async {
    if (model.inTransportMode) {
      Get.dialog(
          AppDialog(
              title: "提示".tr,
              message:
              "功率计正处于运输模式。连接充电线进行充电，或连续转动曲柄10圈，即可退出运输模式。"
                  .tr,
              submit: "确定".tr),
          barrierDismissible: false);
    } else {
      ObjectId? rightDeviceId;
      if (model.rightDeviceModel != null){
        RealmDeviceEntity entity = model.rightDeviceModel!.toEntity();
        rightDeviceId = await saveOrUpdateEntity(entity);
      }
      RealmDeviceEntity entity = model.toEntity();
      entity.rightDeviceId = rightDeviceId;
      saveOrUpdateEntity(entity);

      Get.back(result: model);
    }

  }

  Future<ObjectId> saveOrUpdateEntity(RealmDeviceEntity entity)async{

    var result = realm.all<RealmDeviceEntity>().query("name == '${entity.name}'");
    await realm.writeAsync(() {
      if (result.isEmpty) {
        realm.add(entity, update: false);
      } else {
        entity.id = result.first.id;
        realm.add(entity, update: true);
      }
    });
    result = realm.all<RealmDeviceEntity>().query("name == '${entity.name}'");
    return result.first.id;
  }

}
